<template>
  <div id="map">
    <button @click="goWuHan">去武汉</button>
    <button @click="moveUp">向上移动</button>
    <button @click="moveDown">向下移动</button>
    <button @click="moveLeft">向左移动</button>
    <button @click="moveRight">向右移动</button>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import { XYZ } from 'ol/source';
import 'ol/ol.css';
let map: Map | null = null;
const source = new XYZ({
  // 使用高德地图数据源
  url: 'https://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
})

const layer = new TileLayer({
  source: source
})
const view = new View({
  center: [116.403851, 39.915168], // 北京市中心坐标
  zoom: 11,
  projection: 'EPSG:4326', // 使用Web Mercator投影
  extent: [73.66, 3.86, 135.05, 53.55] // 中国范围
})
onMounted(() => {
  map = new Map({
    target: 'map',
    layers: [layer],
    view: view
  });
});

// 跳转到武汉
const goWuHan = () => {
  if (map) {
    // map.getView().setCenter([114.29935, 22.54744]);
    // map.getView().setZoom(12);
    // 动画效果
    map.getView().animate({
      center: [114.29935, 22.54744],
      zoom: 6,
      duration: 1000 // 动画持续时间，单位毫秒
    });
  }
};
// 向上移动地图
const moveUp = () => {
  if (map) {
    const view = map.getView();
    const currentCenter = view.getCenter();
    if (currentCenter) {
      view.setCenter([currentCenter[0], currentCenter[1] + 0.1]);
    }
  }
};
// 向下移动地图
const moveDown = () => {
  if (map) {
    const view = map.getView();
    const currentCenter = view.getCenter();
    if (currentCenter) {
      view.setCenter([currentCenter[0], currentCenter[1] - 0.1]);
    }
  }
};
// 向左移动地图
const moveLeft = () => {
  if (map) {
    const view = map.getView();
    const currentCenter = view.getCenter();
    if (currentCenter) {
      view.setCenter([currentCenter[0] - 0.1, currentCenter[1]]);
    }
  }
};
// 向右移动地图
const moveRight = () => {
  if (map) {
    const view = map.getView();
    const currentCenter = view.getCenter();
    if (currentCenter) {
      view.setCenter([currentCenter[0] + 0.1, currentCenter[1]]);
    }
  }
};
</script>

<style scoped>
#map {
  width: 100%;
  height: 100%;
}
</style>
